package com.ia.aistream.manager.operating.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ia.aistream.common.utils.StringUtils;
import com.ia.aistream.common.utils.spring.SpringUtils;
import com.ia.aistream.manager.framework.util.ShiroUtils;
import com.ia.aistream.manager.operating.conf.DocMapConf;
import com.ia.aistream.manager.operating.util.convert.DocHandleBusiness;
import com.ia.aistream.manager.operating.util.style.DocStyleUtil;
import com.ia.aistream.manager.operating.util.style.DocTableStyle;
import com.ia.aistream.manager.operating.util.tools.DocToolUtil;
import com.ia.aistream.mapper.operating.DocAppendixSubMapper;
import com.ia.aistream.mapper.operating.DocTitleMapper;
import com.ia.aistream.model.operating.dto.ParagraphTextStyle;
import com.ia.aistream.model.operating.dto.convert.ConvertDto;
import com.ia.aistream.model.operating.entity.DocAppendix;
import com.ia.aistream.model.operating.entity.DocAppendixParagraph;
import com.ia.aistream.model.operating.entity.DocAppendixSub;
import com.ia.aistream.model.operating.entity.DocTitle;
import com.spire.doc.Table;
import com.spire.doc.TableCell;
import com.spire.doc.collections.DocumentObjectCollection;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.util.*;

/***
 * 实现附录数据的处理
 * @author Ymj
 */
@Slf4j
public class DocAppendixUtil {

    /***
     * 实现附录以后的数据的存储
     * @param docs Docs对象
     * @param tName 标题名
     * @param fileName 文件名称
     * @param result 附录的集合
     * @param pageFlag 分页参数
     * @param imgNum 图片的顺序
     * @param fid 文件的id
     * @param start 开始的章节数
     * @param flag 判断是否为子表
     * @param titleId 标题的id
     * @return
     * @throws Exception
     */
    public static Map<String, Object> getAppendixData(DocumentObjectCollection docs, String tName, String fileName, List<DocAppendix> result,
                                                      int pageFlag,int imgNum, long fid, int start, boolean flag, String titleId, int startRow, int titleIndex, int appParIndex) throws Exception {
        Map<String, Object> map = new HashMap<>();

        int i;
        int index=0;
//        int appParIndex = 1;
        boolean appFlag = true;
        String tpId = null;
        // 定义附录段落的集合
        List<DocAppendixParagraph> parList = new ArrayList<>();
        // 附录以后的数据在这里遍历
        for(i=start; i<docs.getCount(); i++){

            // 判断是否为表格
            if(docs.get(i).getDocumentObjectType().equals(DocumentObjectType.Table)){
                Table appTable = (Table)docs.get(i);

                // 获取第一行第一列的第一段
                Paragraph paragraph = appTable.getRows().get(startRow).getCells().get(0).getParagraphs().get(0);

                String content = paragraph.getText().trim();
                String listText = paragraph.getListText().trim();
                // 判断第一行是不是标题
                if(DocStyleUtil.isTitle(paragraph)==1 && !content.endsWith("附录")){
                    break;
                }else if(content.endsWith("附录") && appFlag){
                    // 将标题数据保存到数据库
                    String titleName = "";
                    if(!StringUtils.isEmpty(listText)){
                        titleName = listText + "  " + content;
                    }else{
                        titleName = content;
                    }
                    Map<String, Object> psMap = DocStyleUtil.getParagraphStyle(
                            appTable.getRows().get(startRow).getCells().get(0).getParagraphs().get(0), fileName, 0, fid, tName);
                    JSONObject jsonObject = (JSONObject) JSONObject.toJSON(psMap.get(DocMapConf.DOC_PARAGRAPH_STYLE.value));
                    titleIndex++;
                    DocTitle docTitle = DocFileData.saveTitle(titleName, fid, jsonObject, 4, titleIndex);
                    titleId = docTitle.getId();
                    tName = titleName;
                    index =0;
//                    appParIndex = 1;
                    flag = false;
                    appFlag = false;
                }
//                else if (content.endsWith("附录") && !appFlag && appTable.getRows().getCount()<3){
//                    continue;
//                }
                // 判断表格类型
                //  处理子表数据
                if(flag && DocStyleUtil.isTitle(appTable.getRows().get(0).getCells().get(0).getParagraphs().get(0))==0){
                    // 插入一条引用数据
                    DocAppendixParagraph docAppendixParagraph = new DocAppendixParagraph();
                    docAppendixParagraph.setId(DocToolUtil.getUUID());
                    docAppendixParagraph.setConType(1);
                    docAppendixParagraph.setCreateBy(ShiroUtils.getLoginName());
                    docAppendixParagraph.setCreateTime(new Date());
                    docAppendixParagraph.setDocTitleId(titleId);
                    docAppendixParagraph.setStepNum(appParIndex++);
                    String appId = docAppendixParagraph.getId();
                    parList.add(docAppendixParagraph);
                    Map<String, Object> docAppendixSubMap = DocSubTableUtil.getDocAppendixSub(appTable, appId);
                    List<DocAppendixSub> docAppendixSub = (List<DocAppendixSub>) docAppendixSubMap.get(DocMapConf.DOC_APPENDIX_SUBTABLE_LIST.value);

                    DocAppendixSubMapper docAppendixSubMapper = SpringUtils.getBean("docAppendixSubMapper");

                    int i1 = docAppendixSubMapper.insertDocAppendixSubList(docAppendixSub);
                    if(docAppendixSubMap.containsKey("endRows")){
                        startRow = (int) docAppendixSubMap.get("endRows");
                        i--;
                        flag = false;
                        continue;
                    }
                    if (i1<1){
                        log.error("附录子表数据添加失败..;标题是：" + titleId);
                    }
//                    flag = false;
                }else{
                    Map<String, Object> mapApp = getAppendixTableData(appTable, startRow, titleId, fid, index, tName, pageFlag, titleIndex);
                    tName = (String) mapApp.get("tName");
                    titleIndex = (int) mapApp.get("titleIndex");
                    if(mapApp.containsKey("titleId")){
                        titleId = (String) mapApp.get("titleId");
                    }
                    if(mapApp.containsKey("pageFlag")){
                        pageFlag = (int) mapApp.get("pageFlag");
                    }
                    if(mapApp.containsKey("appendixType")){
                        flag = true;
                    }
                    if(mapApp.containsKey("appendixList")){
                        result.addAll((List<DocAppendix>)mapApp.get("appendixList"));
                        index = (int) mapApp.get("index");
                    }
                }
                startRow = 0;
            }else if(docs.get(i).getDocumentObjectType().equals(DocumentObjectType.Paragraph)) {
                Paragraph paragraph = (Paragraph) docs.get(i);
                int type=3;
                // 判断是否为标题数据 // 先判断是否为空 再处理其他数据
                int title = DocStyleUtil.isTitle(paragraph);
                String titleName = paragraph.getListText().trim() + "  " + paragraph.getText().trim();
                // 处理段落信息
                if(title!=0 && titleName.trim().startsWith("附录")) {
                    titleName = titleName.trim();
                    Map<String, Object> psMap = DocStyleUtil.getParagraphStyle(paragraph, fileName, 0, fid, tName);
                    JSONObject jsonObject = (JSONObject) JSON.toJSON(psMap.get(DocMapConf.DOC_PARAGRAPH_STYLE.value));
                    if(docs.get(i+1).getDocumentObjectType().equals(DocumentObjectType.Table)){
                        type = 2;
                    }
                    titleIndex++;
                    DocTitle docTitle = DocFileData.saveTitle(titleName, fid, jsonObject, type, titleIndex);
                    titleId = docTitle.getId();

                    tName = titleName;
                    if (docTitle.getTitleType().equals(3)){
                        flag = true;
                    }else {
                        flag = false;
                    }
//                    if(titleName.endsWith("附录")){
//                        appParIndex=1;
//                    }
                    index=0;
                    continue;
                }
                // 实现Id的查询，然后根据Id的查询，实现
                DocTitleMapper docTitleMapper = SpringUtils.getBean("docTitleMapper");
                DocTitle docTitle = docTitleMapper.selectDocTitleById(titleId);

                /*************************  **********************************************/
               if(docTitle!=null){
                   Integer titleType = docTitle.getTitleType();

                   if(titleType==2){
                       DocAppendix docAppendix = new DocAppendix();
                       docAppendix.setId(DocToolUtil.getUUID());
                       docAppendix.setStepNum(++index);
                       docAppendix.setPageFlag(pageFlag);
                       docAppendix.setTabFlag(0);
                       docAppendix.setCreateTime(new Date());
                       docAppendix.setRowNum(1L);
                       docAppendix.setRowType(5L);
                       docAppendix.setDocTitleId(titleId);
                       tpId = titleId;
                       titleId = docAppendix.getId();
                       docAppendix.setCreateBy(ShiroUtils.getLoginName());
                       result.add(docAppendix);
                   }
               }

                // 实现附录数据存储
                Map<String, Object> aMap = getAppendixParagraph(paragraph, titleId, fileName, imgNum, fid, tName, appParIndex);
                imgNum = (int) aMap.get(DocMapConf.DOC_IMG_NUM.value);
                if(aMap.containsKey(DocMapConf.DOC_APPENDIX_PARAGRAPH.value)){
                    parList.add((DocAppendixParagraph)aMap.get(DocMapConf.DOC_APPENDIX_PARAGRAPH.value));
                    appParIndex++;
                }
                if (!StringUtils.isEmpty(tpId)){
                    titleId = tpId;
                    tpId = null;
                }
            }
        }

        map.put("index", index);
        map.put("pageFlag", pageFlag);
//        map.put(DocMapConf.DOC_APPENDIX.value, result);
        map.put(DocMapConf.DOC_IMG_NUM.value, imgNum);
        map.put("tName", tName);
        map.put("start", i);
        map.put("titleIndex", titleIndex);
        map.put("appParIndex", appParIndex);
        map.put(DocMapConf.DOC_APPENDIX_PAR_LiST.value, parList);

        return map;
    }

    /***
     * 获取附录段落数据
     * @param paragraph
     * @param titleId
     * @return
     */
    public static Map<String, Object> getAppendixParagraph(Paragraph paragraph, String titleId, String fileName, int imgNum, Long fid, String tName, int appParIndex) throws Exception {
        DocAppendixParagraph docAppendixParagraph = new DocAppendixParagraph();
        Map<String, Object> map = new HashMap<>();
        // 获取段落内容
        String content = paragraph.getText().trim();

        if(!StringUtils.isEmpty(content) ||  paragraph.getChildObjects().getCount()>0){
            // 获取转义后的内容
            ConvertDto paragraphConvert = DocHandleBusiness.getParagraphConvert(paragraph);
            Map<String, Object> psMap = DocStyleUtil.getParagraphStyle(paragraph, fileName, imgNum, fid, tName);
            imgNum = (int) psMap.get(DocMapConf.DOC_IMG_NUM.value);
            docAppendixParagraph.setContent(content);
            if(paragraphConvert!=null){
                docAppendixParagraph.setContentC(paragraphConvert.toString());
            }
            docAppendixParagraph.setContentStyle((JSONObject) JSON.toJSON(psMap.get(DocMapConf.DOC_PARAGRAPH_STYLE.value)));
            docAppendixParagraph.setConType(0);
        }else{
            docAppendixParagraph.setConType(2);
        }

        docAppendixParagraph.setStepNum(appParIndex);
        docAppendixParagraph.setDocTitleId(titleId);
        docAppendixParagraph.setCreateBy(ShiroUtils.getLoginName());
        docAppendixParagraph.setCreateTime(new Date());
        docAppendixParagraph.setId(DocToolUtil.getUUID());
        map.put(DocMapConf.DOC_IMG_NUM.value, imgNum);

//        if(docAppendixParagraph.getContent()==null && docAppendixParagraph.getContentStyle()==null &&
//                docAppendixParagraph.getContentStyle().toJavaObject(ParagraphTextStyle.class).getTextInfoList().size()==0){
        if(docAppendixParagraph.getContentStyle()==null || docAppendixParagraph.getContentStyle().toJavaObject(ParagraphTextStyle.class).getTextInfoList().size()==0){
            return map;
        }
        // 将数据保存到数据库
        map.put(DocMapConf.DOC_APPENDIX_PARAGRAPH.value, docAppendixParagraph);
        // 返回当前段落的Id
        return map;
    }

    /****
     * 获取附录信息
     * @param table
     * @param startRow
     * @param tid
     * @param fid
     * @param index
     * @param tName
     * @param pageFlag
     * @param titleIndex
     * @return
     * @throws UnsupportedEncodingException
     */
    public static Map<String,Object> getAppendixTableData(Table table, int startRow, String tid, long fid, int index, String tName, Integer pageFlag, int titleIndex) throws UnsupportedEncodingException {
        Map<String,Object> map = new HashMap<>();
        List<DocAppendix> appendixList = new ArrayList<>();
        int colsMax = 0;
        int currentRow = 3;
        int rowsMerMax = 0;
        int tabFlag = index+1;
        int count = table.getRows().getCount();
        // 循环遍历所有的数据
        for (int r=startRow; r< table.getRows().getCount(); r++){
            // 判断是否为标题
            String trim = table.getRows().get(r).getCells().get(0).getParagraphs().get(0).getText().trim();
            if(trim.endsWith("附录")){
                int count1 = table.getRows().get(r).getCells().get(0).getParagraphs().getCount();
                if(count1>1){
                    if(DocStyleUtil.isTitle(table.getRows().get(r).getCells().get(0).getParagraphs().get(1))==2){
                        String titleName = table.getRows().get(r).getCells().get(0).getParagraphs().get(1).getText().trim();
                        // 获取单元格样式
                        JSONObject jSONObject = DocStyleUtil.getTitleColumnStyle(table, r, 0, 1);
                        titleIndex++;
                        DocTitle docTitle = DocFileData.saveTitle(titleName, fid, jSONObject, 2, titleIndex);
                        tid = docTitle.getId();
                        tName = titleName;
                        map.put("titleId", tid);
                        index = 1;
                        pageFlag ++;
                    }
                }else{
                    tName = trim;
                }
                continue;
            }

            // 判断是否为标题
            if(DocStyleUtil.isTitle(table.getRows().get(r).getCells().get(0).getParagraphs().get(0))==2){
                // int type = 2;
                // 处理二级标题问题
                String titleName = DocIndex.getCellContent(table.getRows().get(r).getCells().get(0));
                // 获取单元格样式
                JSONObject jSONObject = DocStyleUtil.getColumnStyle(table, r, 0);
                if(table.getRows().getCount()<3+r){
                    titleIndex++;
                    DocTitle docTitle = DocFileData.saveTitle(titleName, fid, jSONObject, 3, titleIndex);
                    tid = docTitle.getId();
                    tName = titleName;
                    map.put("titleId", tid);
                    map.put("tName", tName);
                    map.put("appendixType", "parGraph");
                    map.put("titleIndex", titleIndex);
                    map.put("appendixList", appendixList);
                    map.put("index", index);
                    return map;
                }
                titleIndex++;
                DocTitle docTitle = DocFileData.saveTitle(titleName, fid, jSONObject, 2, titleIndex);
                tid = docTitle.getId();
                map.put("titleId", tid);
                // 二级标题是否进行换行
//                tabFlag++;
                index = 1;
                pageFlag ++;
                continue;
            }

            DocAppendix docAppendix = new DocAppendix();
            docAppendix.setId(DocToolUtil.getUUID());
            docAppendix.setRowNum((long)table.getRows().get(r).getCells().getCount());
            // 设置行的序号
            docAppendix.setStepNum(++index);

            docAppendix.setCreateBy(ShiroUtils.getLoginName());
            docAppendix.setCreateTime(new Date());
            docAppendix.setDocTitleId(tid);

            // 设置类型为内容
            docAppendix.setRowType(0L);
            docAppendix.setPageFlag(pageFlag);
            if(colsMax==0){
                colsMax = DocStyleUtil.getColsMax(table, r);
            }
            if(table.getRows().get(r).getCells().getCount()==colsMax || r < currentRow){

                docAppendix.setTabFlag(tabFlag);
                // 循环列数据
                for(int c=0; c<table.getRows().get(r).getCells().getCount(); c++){
                    TableCell tableCell = table.getRows().get(r).getCells().get(c);
                    /*************************
                     * 获取某一单元格的合并行数 NULL
                     *****************************/
                    Integer rowsMerge = DocTableStyle.getRowsMerge(table, r, c);
                    if(rowsMerge!=null && rowsMerge>rowsMerMax){
                        currentRow= (r + rowsMerge)-1;
                        rowsMerMax = rowsMerge;
                    }

                    // 获取单元格内容
                    String cellContent = DocIndex.getCellContent(tableCell);
                    // 获取单元格的样式
                    JSONObject columnStyle = DocStyleUtil.getAppendixColumnStyle(table, r, c, colsMax);
                    if(columnStyle==null){
                        continue;
                    }
                    int underCount = 0;
                    if(columnStyle.toJSONString().contains("underLine")){
                        String[] split = columnStyle.toJSONString().split("underLine");
                        underCount = split.length - 1;
                    }
                    String s = tableCell.getCellFormat().getVerticalMerge().toString();
                    if(s.equals("Continue")){
                        columnStyle = null;
                    }
                    // 获取单元格转义后的数据
                    ConvertDto tableConvertContent = DocHandleBusiness.getTableConvertContent(tableCell, underCount);
                    String convet = null;
                    if(tableConvertContent!=null){
                        convet = tableConvertContent.toString();
                    }
                    switch(c){
                        case 0:
                            docAppendix.setC1O(cellContent);
                            docAppendix.setC1Style(columnStyle);
                            docAppendix.setC1C(convet);
                            break;
                        case 1:
                            docAppendix.setC2O(cellContent);
                            docAppendix.setC2Style(columnStyle);
                            docAppendix.setC2C(convet);
                            break;
                        case 2:
                            docAppendix.setC3O(cellContent);
                            docAppendix.setC3Style(columnStyle);
                            docAppendix.setC3C(convet);
                            break;
                        case 3:
                            docAppendix.setC4O(cellContent);
                            docAppendix.setC4Style(columnStyle);
                            docAppendix.setC4C(convet);
                            break;
                        case 4:
                            docAppendix.setC5O(cellContent);
                            docAppendix.setC5Style(columnStyle);
                            docAppendix.setC5C(convet);
                            break;
                        case 5:
                            docAppendix.setC6O(cellContent);
                            docAppendix.setC6Style(columnStyle);
                            docAppendix.setC6C(convet);
                            break;
                        case 6:
                            docAppendix.setC7O(cellContent);
                            docAppendix.setC7Style(columnStyle);
                            docAppendix.setC7C(convet);
                            break;
                        case 7:
                            docAppendix.setC8O(cellContent);
                            docAppendix.setC8Style(columnStyle);
                            docAppendix.setC8C(convet);
                            break;
                        case 8:
                            docAppendix.setC9O(cellContent);
                            docAppendix.setC9Style(columnStyle);
                            docAppendix.setC9C(convet);
                            break;
                        case 9:
                            docAppendix.setC10O(cellContent);
                            docAppendix.setC10Style(columnStyle);
                            docAppendix.setC10C(convet);
                            break;
                        case 10:
                            docAppendix.setC11O(cellContent);
                            docAppendix.setC11Style(columnStyle);
                            docAppendix.setC11C(convet);
                            break;
                        case 11:
                            docAppendix.setC12O(cellContent);
                            docAppendix.setC12Style(columnStyle);
                            docAppendix.setC12C(convet);
                            break;
                        case 12:
                            docAppendix.setC13O(cellContent);
                            docAppendix.setC13Style(columnStyle);
                            docAppendix.setC13C(convet);
                            break;
                        case 13:
                            docAppendix.setC14O(cellContent);
                            docAppendix.setC14Style(columnStyle);
                            docAppendix.setC14C(convet);
                            break;
                        case 14:
                            docAppendix.setC15O(cellContent);
                            docAppendix.setC15Style(columnStyle);
                            docAppendix.setC15C(convet);
                            break;
                        default:
                            System.out.println("请联系管理员添加数据");
                            break;
                    }
                }
                appendixList.add(docAppendix);
            } else{
                //获取4行列的最大长度
                colsMax = DocStyleUtil.getColsMax(table, r);
                tabFlag = index;
                rowsMerMax = 0;
                currentRow = r+2;
                index--;
                r--;
            }
        }

        map.put("appendixList", appendixList);
        map.put("index", index);
        map.put("pageFlag", pageFlag);
        map.put("tName", tName);
        map.put("titleIndex", titleIndex);
        return map;
    }

}
